package com.ws.shop.service.impl;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.ws.shop.bean.HtmlConfig;
import com.ws.shop.bean.Page;
import com.ws.shop.dao.MallDao;
import com.ws.shop.entity.Mall;
import com.ws.shop.entity.Order;
import com.ws.shop.service.HtmlService;
import com.ws.shop.service.MallService;
import com.ws.shop.util.CommonUtil;
import com.ws.shop.util.StringUtil;
import com.ws.shop.util.TemplateConfigUtil;

@Service(value="mallService")
public class MallServiceImpl implements MallService {
	@Resource(name="mallDao")
	private MallDao mallDao;
	@Autowired
	private HtmlService htmlService;

	@Cacheable(value="mallColl")
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Page findMallPageByTitle(int pageno,int pagesize, String title) {
		return mallDao.findMallPageByTitle(pageno,pagesize,title);
	}

	@CacheEvict(value="mallColl",allEntries=true)
	@Transactional(rollbackFor=Exception.class)
	public void saveOrUpdate(Mall mall) {
		if(StringUtil.isEmpty(mall.getHtml())){
			HtmlConfig htmlConfig = TemplateConfigUtil.getHtmlConfig(HtmlConfig.MALL_DETAIL);
			String htmlFilePath = htmlConfig.getHtmlFilePath(CommonUtil.getRandomString(8));
			mall.setHtml(htmlFilePath);
		}
		mallDao.saveOrUpdate(mall);
		//生成静态页
		htmlService.mallDetailBuildHtml(mall);
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Mall findMallById(int id) {
		return mallDao.findMallById(id);
	}

	@CacheEvict(value="mallColl",allEntries=true)
	@Transactional(rollbackFor=Exception.class)
	public Object[] integralConversion(final Order order){
		return mallDao.integralConversion(order);
	}

	@Cacheable(value="mallColl")
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Page findMallPage(int pageno, int pagesize, int cid, int startScore,
			int endScore,int state) {
		return mallDao.findMallPage(pageno, pagesize, cid, startScore, endScore,state);
	}

	@CacheEvict(value="mallColl",allEntries=true)
	@Transactional(rollbackFor=Exception.class)
	public void updateState(int id, int state) {
		mallDao.updateState(id,state);
	}
}
